//拦截器

const path = require("path");

const utils = require("../utils/utils");

let whiteList = require(path.resolve(__basename, "whiteList/whiteList.js"));

module.exports = (app) => {
  //处理OPTIONS(浏览器嗅探服务器支持的请求类型)
  app.use((req, res, next) => {
    if (req.method === "OPTIONS") {
      return res.send(true);
    }
    next();
  });

  //验证码验证拦截器
  app.use((req, res, next) => {
    // console.log("req.body==>", req.body);
    if (whiteList.validCodeWhiteList.indexOf(req.url) > -1) {
      // console.log("需要验证验证码");
      //findOne普通对象
      //findAll数据对象
      model.ValidCode.findOne({
        attributes: ["email", "validCode", "createdAt"],
        where: {
          validCodeId: req.body.validCodeId,
        },
      })
        .then((result) => {
          // console.log("req.body.email==>", req.body.email);
          //邮箱、验证码、时间三个条件必须成立
          if (result.dataValues.email !== req.body.email) {
            return res.send({ msg: "邮箱不正确", code: 1012 });
          }
          if (result.dataValues.validCode !== req.body.validCode) {
            return res.send({ msg: "验证码不正确", code: 1013 });
          }
          let currentTime = new Date().getTime();
          let createdAt = new Date(result.dataValues.createdAt).getTime();
          let time = currentTime - createdAt;
          if (time > CONFIG.VALIDCODE_OPTIONS.EXPIRES) {
            return res.send({ msg: "验证码已失效", code: 1014 });
          }
          // res.send({ msg: "验证码正确", code: 1010 });
          //验证验证通过, 继续访问下一个中间件或者路由
          next();
        })
        .catch((err) => {
          console.log("err==>", err);
          res.send({ msg: "验证码不正确", code: 1011 });
        });
    } else {
      // console.log("无需验证验证码");
      next();
    }
  });

  // 拦截token, 登录验证
  app.use((req, res, next) => {
    // console.log('req.url ==> ', req.url);

    let url = req.url;

    if (req.method === "GET") {
      url = url.split("?")[0];
    }

    // console.log('url ==> ', url);

    if (whiteList.tokenWhiteList.indexOf(url) > -1) {
      console.log("需要验证token");
      // console.log("req.headers.token==>", req.headers.token);
      //验证token
      utils
        .verifyToken(req.headers.token)
        .then((result) => {
          // console.log("result ==> ", result);
          //将用户userId传递
          req.userId = result.data;
          next();
        })
        .catch((err) => {
          console.log('err ==> ', err);
          res.send({ msg: "请先登录", code: 1041 });
        });
    } else {
      console.log("无需验证token");
      next();
    }
  });
};
